<?php

/**
 * 试题删除后续操作
 * 触发位置：学科删除、章节删除、题目纠错删除
 */

namespace App\Jobs;

use App\Models\Qh_Question;
use App\Service\Redis\RedisBaseService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;

class QuestionDeleteHelperJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected Qh_Question $question;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($question)
    {
        $this->question = $question;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle(RedisBaseService $redisBaseService)
    {
        try {
            \DB::transaction(function () use ($redisBaseService) {
                // 试题数量更新
                updateQhQuestionCount($this->question->knowledgeId, 1, 2);

                $questionId = $this->question->id;

                // 从错题集中删除
                // foreach (DB::table('qh_user_wrong_questions')->select('userId')->get() as $log) {
                //     $redisBaseService->popWrongOrCollectQuestion($log->userId, $this->question, 1);
                // }
                // DB::table('qh_user_wrong_questions')->select('userId')->get()->each(function ($log) use ($redisBaseService) {
                //     $redisBaseService->popWrongOrCollectQuestion($log->userId, $this->question, 1);
                // });
                QuestionDeleteHelper1Job::dispatch($this->question);

                // 从收藏中删除
                // foreach (DB::table('qh_user_collect_questions2')->select('userId')->get() as $log) {
                //     $redisBaseService->popWrongOrCollectQuestion($log->userId, $this->question, 2);
                // }
                // DB::table('qh_user_collect_questions2')->select('userId')->get()->each(function ($log) use ($redisBaseService) {
                //     $redisBaseService->popWrongOrCollectQuestion($log->userId, $this->question, 2);
                // });
                QuestionDeleteHelper2Job::dispatch($this->question);

                // 从表中删除：qh_user_question_logs、qh_user_learn_question_logs、qh_user_collect_questions、
                QuestionDeleteHelper4Job::dispatch($this->question);
                QuestionDeleteHelper5Job::dispatch($this->question);
                QuestionDeleteHelper6Job::dispatch($this->question);

                // 删除试题本身
                QuestionDeleteHelper7Job::dispatch($this->question);
                // 删除笔记和评论
                QuestionDeleteHelper8Job::dispatch($questionId);
            }, 5);
            \Log::debug('[试题删除事件]处理完成:QuestionId:'.$this->question->id);
        } catch (\Throwable $e) {
            \Log::error('[试题删除事件]处理失败'. $e->getMessage());
        }
    }
}
